import * as React from "react"
import { useHistory, useParams, useLocation } from "react-router-dom"
import {
  Table,
  Form,
  Button,
  Menu,
  Dropdown,
  Tag,
  message,
  Breadcrumb
} from "antd"
import { SettingOutlined, PlusOutlined } from "@ant-design/icons"
import { ColumnProps } from "antd/lib/table"
import style from "./style.module.css"
import { Education, ICompany, IRecruit, SkuStatus, Year } from "../../types"
import Edit from "./Edit"
import * as api from '../../services/api'
import { toFontEducation, toFontYear } from "../util"

interface Params {
  id: string
}

export default function Recruit() {
  const path = useLocation().pathname
  const [data, setData] = React.useState<IRecruit[]>([])
  const [record, setRecord] = React.useState<IRecruit>()
  const [company, setCompany] = React.useState<ICompany>()
  //是否决定传入record参数
  const [flag, setFlag] = React.useState<boolean>(true)
  const [visible, setVisible] = React.useState<boolean>(false)
  const history = useHistory()
  const id = useParams<Params>().id
  const getData = async () => {
    try {
      const handle = message.loading('正在加载数据...', 0)
      const res = await api.recruitlist(id)
      const res2 = await api.company('token')
      if (res.stat === 'OK') {
        setData(res.rows)
        handle()
      }
      if (res2.stat === 'OK') {
        setCompany(res2.result)
      }
    } catch (error) {
      console.trace(error)
    }
  }
  React.useEffect(() => {
    const getData = async () => {
      const handle = message.loading('正在加载数据...', 0)
      const res = await api.recruitlist(id)
      const res2 = await api.company('token')
      if (res.stat === 'OK') {
        setData(res.rows)
      }
      if (res2.stat === 'OK') {
        setCompany(res2.result)
      }
      handle()
    }
    getData()
  }, [id])

  //如果外面没有调用record,编辑就不能渲染record
  console.log(flag ? record : 'hh')
  const columns: ColumnProps<IRecruit>[] = [
    {
      title: '职位名称',
      dataIndex: 'positionName',
      align: 'center',
      width: 100
    },
    {
      title: '薪水',
      dataIndex: 'salary',
      width: 100,
      render: (value: { min: number, max: number }) => {
        return (
          <div className={style.salary}>
            {value.min + `-` + value.max}K
          </div>
        )
      }
    },
    {
      title: '城市',
      width: 100,
      dataIndex: 'city'
    },
    {
      title: '工作经验',
      dataIndex: 'workYear',
      width: 100,
      render: (value: Year) => {
        return toFontYear(value)
      }
    },
    {
      title: '学历',
      dataIndex: 'education',
      render: (value: Education) => {
        return toFontEducation(value)
      }
    },
    {
      title: '创建时间',
      width: 150,
      dataIndex: 'time'
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      width: 150
    },
    {
      title: '状态',
      dataIndex: 'isDisabled',
      render: ((value: SkuStatus) => {
        if (value === SkuStatus.Normal) return <Tag color='green'>上架</Tag>
        else return <Tag color='red'>下架</Tag>
      })
    },
    {
      title: '标签',
      dataIndex: 'keyWords',
      render: (value: string[]) => {
        return (
          <div className={style.keys}>
            {value?.map((item) => {
              return <Tag>{item}</Tag>;
            })}
          </div>
        )
      }
    },
    {
      title: '操作',
      key: 'opt',
      width: 150,
      align: 'center',
      render: (val, record) => {
        return (
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item
                  key="view"
                  onClick={() =>
                    history.push(
                      `${path}/view/${record._id}`
                    )
                  }
                >
                  查看
                </Menu.Item>
                <Menu.Item key="edit" onClick={() => {
                  setRecord(record)
                  setVisible(!visible)
                }}
                  disabled={company?.isDisabled === 2 || company === undefined}
                >
                  编辑
                </Menu.Item>
                <Menu.Item key="delete" onClick={async () => {
                  const res = await api.removeRecruit(record._id)
                  if (res.stat === 'OK') {
                    message.success('删除成功')
                    getData()
                  }
                }}
                  disabled={company === undefined}
                >
                  删除
                </Menu.Item>
              </Menu>
            }
          >
            <Button icon={<SettingOutlined />} />
          </Dropdown>
        )
      }
    }
  ]
  return (
    <>
      <Breadcrumb>
        <Breadcrumb.Item>
          {company === undefined ? '还没有公司雇用你，你不能发布职位' : '我所在的公司'}
        </Breadcrumb.Item>
        <Breadcrumb.Item>{company?.companyShortName}</Breadcrumb.Item>
        {company?.isDisabled === 2 && <Breadcrumb.Item>此公司已被禁用，您不能发布职位</Breadcrumb.Item>}
      </Breadcrumb>
      <Form layout="inline" className={style.toolbar}>
        <Form.Item>
          <Button
            type="primary"
            onClick={() => {
              setFlag(false)
              setVisible(!visible)
            }}
            icon={<PlusOutlined />}
            disabled={company === undefined || company.isDisabled === 2}
          >
            添加职位
          </Button>
        </Form.Item>
      </Form>
      <Table
        dataSource={data}
        rowKey='_id'
        columns={columns}
      />
      {visible && (
        <Edit
          getData={getData}
          record={flag ? record : undefined}
          afterClose={() => {
            setVisible(false)
            setFlag(true)
          }}
        />
      )}
    </>
  )
}
